//默认的GET Header
const _GET_ = () =>  {
    return {
        method: 'GET',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        }
    }
}

// //默认的POST Header
// const _POST_ = (body: any) => {
//     return(
//             {
//                 method: 'POST',
//                 headers: {
//                     'Accept': 'application/json',
//                     'Content-Type': 'application/json'
//                 },
//                 body: JSON.stringify(body)
//             } 
//         )
// }

// //默认的PUT Header
// const _PUT_ = (body: any) => {
//     return(
//         {
//             method: 'PUT',
//             headers: {
//                 'Accept': 'application/json',
//                 'Content-Type': 'application/json'
//             },
//             body: JSON.stringify(body)
//         } 
//     )
// }

//通用的请求生成器
class Requester {
    host: string;
    url: string;
    header: any;

    constructor(header={}, url: string) {
        this.host = 'https://cnodejs.org/api/v1'
        this.url = url
        this.header = header
    }

    do_fetch () {
        return new Promise((resolve, reject) => {
            let timeout = setTimeout(() => {reject("请求超时")}, 20000)
            let _url = `${this.host}${this.url}` 
            console.log('_url', _url)
            fetch(_url, this.header).then((response) => {
                clearTimeout(timeout)
            if (response.status.toString().match(/^2.*/)) {
                    return response.json()
                } else {
                    return reject(response.status)
                }
            }).then((responseData) => {
                return resolve(responseData)
            }).catch((error) => {
                return reject(error)
            })
        })
    }
}

export const topicListApi = (page=1, tab='', limit=20) => {
    return new Requester(_GET_(), `/topics?page=${page}&tab=${tab}&limit=${limit}`).do_fetch()
}

export const topicDetailApi = (id: string) => {
    return new Requester(_GET_(), `/topic/${id}`).do_fetch()
}

